package com.ruicar.afs.cloud.account.common.processor.impl.msg;

import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.account.common.entity.AccountVoucherInfo;
import com.ruicar.afs.cloud.account.common.processor.AbsBaseProcessor;
import com.ruicar.afs.cloud.account.common.processor.IRequest;
import com.ruicar.afs.cloud.account.common.processor.enums.VoucherMsgType;
import com.ruicar.afs.cloud.account.common.processor.impl.VoucherRequest;
import com.ruicar.afs.cloud.account.common.processor.impl.VoucherResponse;
import com.ruicar.afs.cloud.account.common.service.AccountVoucherInfoService;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.modules.contract.enums.VoucherSendStatus;
import com.ruicar.afs.cloud.voucher.dto.VoucherSendInfoDto;
import com.ruicar.afs.cloud.voucher.feign.VoucherApiFeign;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
@AllArgsConstructor
public class VoucherSendProcessor extends AbsBaseProcessor<VoucherRequest, VoucherResponse> {
    private final VoucherApiFeign voucherApiFeign;
    private final AccountVoucherInfoService accountVoucherInfoService;

    @Override
    public VoucherMsgType msgType() {
        return VoucherMsgType.CONFIDENTIAL_INFORMATION;
    }
    @Override
    public List process(VoucherRequest request) {
        //发送凭证信息
        VoucherResponse response = this.callServer(request);
        List<AccountVoucherInfo> infos =
        request.getDtos().stream().map(accountVoucherInfoDto -> {
            AccountVoucherInfo accountVoucherInfo =accountVoucherInfoDto.getAccountVoucherInfo();
            log.info("凭证信息状态修改,凭证号：[{}]",accountVoucherInfo.getVoucherNo());
            if(CommonConstants.SUCCESS.equals(response.getCode())){
                accountVoucherInfo.setStatus(VoucherSendStatus.SEND_SUCCESS);
                accountVoucherInfo.setSendingDate(new Date());
                accountVoucherInfo.setErrMsg("");
            }else{
                accountVoucherInfo.setStatus(VoucherSendStatus.SEND_FAIL);
                accountVoucherInfo.setErrMsg(response.getMsg());
            }
            return accountVoucherInfo;
        }).collect(Collectors.toList());
        accountVoucherInfoService.updateBatchById(infos);
        return null ;
    }
    @Override
    public IRequest getRequestParams(VoucherRequest request) {
        return request.get();
    }
    @Override
    public VoucherResponse processRsp(JSONObject jsonObject) {
        VoucherResponse response = JSONObject.toJavaObject(jsonObject,VoucherResponse.class);
        return  VoucherResponse.convertFrom(response);
    }

    @Override
    public JSONObject send(IRequest iRequest) {
        return voucherApiFeign.send((List<VoucherSendInfoDto>) iRequest.getData());
    }
}
